package org.piaohao.howtodoit.usermanager;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.jfinal.aop.Clear;
import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import org.apache.catalina.security.SecurityUtil;

import java.io.IOException;
import java.util.List;

public class UserController extends Controller {

    /**
     * 注册
     */
    @Clear(LoginInterceptor.class)
    @ActionKey("/api/v1/sign_up")
    public void signUp() {
        User user = getModel(User.class, "");
        String email = user.getEmail();
        if (!Validator.isEmail(email)) {
            getResponse().setStatus(HttpStatus.HTTP_BAD_REQUEST);
            renderJson(MapUtil.of("errorMsg", "Invalid email"));
            return;
        }
        String password = user.getPassword();
        if (StrUtil.isBlank(password)) {
            getResponse().setStatus(HttpStatus.HTTP_BAD_REQUEST);
            renderJson(MapUtil.of("errorMsg", "Invalid password"));
            return;
        }
        User record = user.findById(email);
        if (record != null) {
            getResponse().setStatus(HttpStatus.HTTP_CONFLICT);
            renderJson(MapUtil.of("errorMsg", "Invalid exists"));
            return;
        }
        user.setPassword(SecureUtil.sha1(password));
        user.save();
        getResponse().setStatus(HttpStatus.HTTP_CREATED);
        renderJson();
    }

    /**
     * 登录
     */
    @Clear(LoginInterceptor.class)
    @ActionKey("/api/v1/login")
    public void login() {
        User user = getModel(User.class, "");
        String email = user.getEmail();
        if (!Validator.isEmail(email)) {
            getResponse().setStatus(HttpStatus.HTTP_BAD_REQUEST);
            renderJson(MapUtil.of("errorMsg", "Invalid email"));
            return;
        }
        String password = user.getPassword();
        if (StrUtil.isBlank(password)) {
            getResponse().setStatus(HttpStatus.HTTP_BAD_REQUEST);
            renderJson(MapUtil.of("errorMsg", "Invalid password"));
            return;
        }
        User record = user.findById(email);
        if (record == null || !record.getPassword().equals(SecureUtil.sha1(password))) {
            getResponse().setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            renderJson(MapUtil.of("errorMsg", "user not exist or password is not right"));
            return;
        }
        getSession().setAttribute(MainApp.Const.SESSION_KEY, record.getEmail());
        getResponse().setStatus(HttpStatus.HTTP_CREATED);
        renderJson();
    }

    /**
     * 退出
     */
    @ActionKey("/api/v1/logout")
    public void logout() {
        getSession().removeAttribute(MainApp.Const.SESSION_KEY);
        getResponse().setStatus(HttpStatus.HTTP_NO_CONTENT);
        renderJson();
    }

    /**
     * 退出
     */
    @ActionKey("/api/v1/sessions")
    public void deleteSessions() {
        getSession().removeAttribute(MainApp.Const.SESSION_KEY);
        getResponse().setStatus(HttpStatus.HTTP_NO_CONTENT);
        renderJson();
    }

    /**
     * 用户列表
     */
    @ActionKey("/api/v1/users")
    public void users() {
        String q = getPara("q");
        String pageStr = getPara("page");
        Integer page = null;
        if (!NumberUtil.isInteger(pageStr) || (page = Convert.toInt(pageStr)) < 0) {
            getResponse().setStatus(HttpStatus.HTTP_BAD_REQUEST);
            renderJson(MapUtil.of("errorMsg", "Invalid page"));
            return;
        }
        StringBuilder sql = new StringBuilder("select * from user where 1=1 ");
        if (StrUtil.isNotBlank(q)) {
            sql.append("and firstName like '%?%'")
                    .append("or lastName like '%?%'");
        }
        SqlPara sqlPara = new SqlPara();
        sqlPara.setSql(sql.toString());
        sqlPara.addPara(q).addPara(q);
        Page<Record> paginate = Db.paginate(page, 10, sqlPara);
        renderJson(paginate.getList());
    }

    /**
     * 用户profile
     */
    @ActionKey("/api/v1/user/")
    public void user() {
        renderJson(User.dao.findById(getPara()));
    }

    /**
     * 用户profile
     */
    @ActionKey("/api/v1/my/profile")
    public void profile() {
        renderJson(User.dao.findById(getSession().getAttribute(MainApp.Const.SESSION_KEY)));
    }

    /**
     * add用户profile
     */
    @ActionKey("/api/v1/users")
    public void addProfile() {
    }

    /**
     * update用户profile
     */
    @ActionKey("/api/v1/users/{userId}")
    public void updateProfile() {
    }

    /**
     * delete用户profile
     */
    @ActionKey("/api/v1/users/{userId}")
    public void deleteProfile() {
    }

}
